package xuegao.study.mall.web.ms;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xuegao.study.mall.common.ms.Item;
import xuegao.study.mall.common.ms.SeckillOrder;
import xuegao.study.mall.common.service.RedisService;
import xuegao.study.mall.repo.dao.pms.PmsSkuStockDao;
import xuegao.study.mall.web.domain.QueueEnum;

import java.util.ArrayList;
import java.util.List;

@Service
public class SeckillService {

    private Logger logger = LoggerFactory.getLogger(SeckillService.class);


    @Autowired
    private RedisService redisService;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private PmsSkuStockDao pmsSkuStockDao;

    public List<Item>  getItems() {
        List<Item> list = new ArrayList<>();
        Item item1 = new Item();
        Item item2 = new Item();
        item1.setId(10001L);
        item1.setName("苹果手机iphone16");
        item1.setStock(100);
        item2.setId(10002L);
        item2.setName("小米19");
        item2.setStock(50);
        list.add(item1);
        list.add(item2);
        return list;
    }

    public boolean seckill(Long itemId, Long userId) {
        //1.检查库存
        String stockKey = "item_stock_" + itemId;
        Long stock = redisService.decr(stockKey, 1);
        if (stock == null || stock < 0) {
            redisService.incr(stockKey, 1);
            return false;
        }
        //2.发送消息到消息队列(秒杀交换机 秒杀队列)
        String sendMessage = JSON.toJSONString(new SeckillOrder(itemId, userId));
        amqpTemplate.convertAndSend(QueueEnum.QUEUE_ORDER_SECKILL.getExchange(), QueueEnum.QUEUE_ORDER_SECKILL.getName(), sendMessage);
        return true;
    }

    @Transactional
    public void createOrder(SeckillOrder seckillOrder) {
        //todo 1.商品扣库存
        Long itemId = seckillOrder.getItemId();
        Long userId = seckillOrder.getUserId();
        logger.info("将会创建商品订单|itemId:" + itemId + "|userId:" + userId);
        //todo 2.生成订单

    }


}
